//
//  AppDelegate+AppService.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/28.
//  Copyright © 2020 吴欧. All rights reserved.
//

#import "AppDelegate+AppService.h"
#import "OpenUDID.h"
#import "HEGuideViewController.h"
#import "HEProtocalViewController.h"
#import "HELoginViewController.h"
#import "AppManager.h"
#import "HEGesturesPWDViewController.h"
#import "HESecurityManage.h"

@implementation AppDelegate (AppService)



#pragma mark ————— 初始化服务 —————
-(void)initService{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNotificationLoginStateChange
                                               object:nil];
    
    //网络状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
}

#pragma mark ————— 初始化window —————
-(void)initWindow{
    
    [NSThread sleepForTimeInterval:1];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = KWhiteColor;
    [self.window makeKeyAndVisible];
    [[UIButton appearance] setExclusiveTouch:YES];
//    [[UIButton appearance] setShowsTouchWhenHighlighted:YES];
    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = KWhiteColor;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

- (void)removeLaunchScreenCacheIfNeeded {
   NSString *filePath = [NSString stringWithFormat:@"%@/Library/SplashBoard", NSHomeDirectory()];
   
   if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];

    if (error) {
         NSLog(@"清除LaunchScreen缓存失败");
       } else {
         NSLog(@"清除LaunchScreen缓存成功");
       }
    }
}

- (void)setupBaiduMap {

    // 初始化定位SDK
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"vjDLgUxrTHYG4NHRNp6dKZcDV1HMqZ3K" authDelegate:self];
    // 否同意隐私合格政策
    [[BMKLocationAuth sharedInstance] setAgreePrivacy:YES];


    // 要使用百度地图，请先启动BaiduMapManager
    self.mapManager = [[BMKMapManager alloc] init];
    [BMKMapManager setAgreePrivacy: YES];
    [BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL];

    // 如果要关注网络及授权验证事件，请设定generalDelegate参数
    BOOL ret = [self.mapManager start:@"vjDLgUxrTHYG4NHRNp6dKZcDV1HMqZ3K" generalDelegate:nil];
    if (!ret) {
       NSLog(@"启动引擎失败");
    }
}

- (void)setupKeyboardManager {
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    
    keyboardManager.enable = YES; // 控制整个功能是否启用
    
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    
    keyboardManager.enableAutoToolbar = NO; // 控制是否显示键盘上的工具条
    
    [keyboardManager canGoNext];
    
//    keyboardManager.shouldShowTextFieldPlaceholder = YES; // 是否显示占位文字
    
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:16]; // 设置占位文字的字体
    
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
}

#pragma mark ————— 初始化网络配置 —————
-(void)NetWorkConfig{
//    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
//    config.baseUrl = URL_main;
}

#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{
    
    BOOL hasShowGuide = [kUserDefaults boolForKey:KHasShowGuide];
        
    if(!hasShowGuide) {
        HEGuideViewController *guideVC = [[HEGuideViewController alloc] init];
        self.window.rootViewController = guideVC;
        return;
    }
    
    NSString *token = [[UserManager sharedUserManager] getToken];
     
    if (token != nil) {
        
        BOOL hasSecurity = [HESecurityManage security];
        if (hasSecurity) {
            return;
        }
        
        self.mainTabBar = [[MainTabBarController alloc] init];
        self.window.rootViewController = self.mainTabBar; 
        [[HESocketManager sharedManager] connect];
    } else {
        self.window.rootViewController = [[HELoginViewController alloc] init];
    }
    
    //展示FPS
//    [AppManager showFPS];
}

//#pragma mark ————— 登录状态处理 —————
//- (void)loginStateChange:(NSNotification *)notification
//{
//    BOOL loginSuccess = [notification.object boolValue];
//    
//    if (loginSuccess) {//登陆成功加载主窗口控制器
//        
//        //为避免自动登录成功刷新tabbar
//        if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[MainTabBarController class]]) {
//            self.mainTabBar = [MainTabBarController new];
//
//            CATransition *anima = [CATransition animation];
//            anima.type = @"cube";//设置动画的类型
//            anima.subtype = kCATransitionFromRight; //设置动画的方向
//            anima.duration = 0.3f;
//            
//            self.window.rootViewController = self.mainTabBar;
//            
//            [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
//            
//        }
//        
//    }else {//登陆失败加载登陆页面控制器
//        
//        self.mainTabBar = nil;
//        RootNavigationController *loginNavi =[[RootNavigationController alloc] initWithRootViewController:[LoginViewController new]];
//        
//        CATransition *anima = [CATransition animation];
//        anima.type = @"fade";//设置动画的类型
//        anima.subtype = kCATransitionFromRight; //设置动画的方向
//        anima.duration = 0.3f;
//        
//        self.window.rootViewController = loginNavi;
//        
//        [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
//        
//    }
//    //展示FPS
//    [AppManager showFPS];
//}
//
//
//#pragma mark ————— 网络状态变化 —————
//- (void)netWorkStateChange:(NSNotification *)notification
//{
//    BOOL isNetWork = [notification.object boolValue];
//    
//    if (isNetWork) {//有网络
//        if ([userManager loadUserInfo] && !isLogin) {//有用户数据 并且 未登录成功 重新来一次自动登录
//            [userManager autoLoginToServer:^(BOOL success, NSString *des) {
//                if (success) {
//                    DLog(@"网络改变后，自动登录成功");
////                    [MBProgressHUD showSuccessMessage:@"网络改变后，自动登录成功"];
//                    KPostNotification(KNotificationAutoLoginSuccess, nil);
//                }else{
//                    [MBProgressHUD showErrorMessage:NSStringFormat(@"自动登录失败：%@",des)];
//                }
//            }];
//        }
//        
//    }else {//登陆失败加载登陆页面控制器
//        [MBProgressHUD showTopTipMessage:@"网络状态不佳" isWindow:YES];
//    }
//}
//
//
//#pragma mark ————— 友盟 初始化 —————
//-(void)initUMeng{
//    /* 打开调试日志 */
//    [[UMSocialManager defaultManager] openLog:YES];
//    
//    /* 设置友盟appkey */
//    [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey];
//    
//    [self configUSharePlatforms];
//}
//#pragma mark ————— 配置第三方 —————
//-(void)configUSharePlatforms{
//    /* 设置微信的appKey和appSecret */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kAppKey_Wechat appSecret:kSecret_Wechat redirectURL:nil];
//    /*
//     * 移除相应平台的分享，如微信收藏
//     */
//    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
//    
//    /* 设置分享到QQ互联的appID
//     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
//     */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kAppKey_Tencent/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
//}
//
//#pragma mark ————— OpenURL 回调 —————
//// 支持所有iOS系统。注：此方法是老方法，建议同时实现 application:openURL:options: 若APP不支持iOS9以下，可直接废弃当前，直接使用application:openURL:options:
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    if (!result) {
//        // 其他如支付等SDK的回调
//    }
//    return result;
//}
//
//// NOTE: 9.0以后使用新API接口
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options];
//    if (!result) {
//        // 其他如支付等SDK的回调
//        if ([url.host isEqualToString:@"safepay"]) {
//            //跳转支付宝钱包进行支付，处理支付结果
////            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
////                NSLog(@"result = %@",resultDic);
////            }];
//            return YES;
//        }
////        if  ([OpenInstallSDK handLinkURL:url]){
////            return YES;
////        }
////        //微信支付
////        return [WXApi handleOpenURL:url delegate:[PayManager sharedPayManager]];
//    }
//    return result;
//}

#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    // 网络状态改变一次, networkStatusWithBlock就会响应一次
//    [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {
//        
//        switch (networkStatus) {
//                // 未知网络
//            case PPNetworkStatusUnknown:
//                DLog(@"网络环境：未知网络");
//                // 无网络
//            case PPNetworkStatusNotReachable:
//                DLog(@"网络环境：无网络");
//                KPostNotification(KNotificationNetWorkStateChange, @NO);
//                break;
//                // 手机网络
//            case PPNetworkStatusReachableViaWWAN:
//                DLog(@"网络环境：手机自带网络");
//                // 无线网络
//            case PPNetworkStatusReachableViaWiFi:
//                DLog(@"网络环境：WiFi");
//                KPostNotification(KNotificationNetWorkStateChange, @YES);
//                break;
//        }
//        
//    }];
    
}

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

- (UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}



@end
